package com.rtx.common;

import org.apache.ibatis.javassist.ClassPool;
import org.apache.ibatis.javassist.CtClass;
import org.apache.ibatis.javassist.CtField;
import org.apache.ibatis.javassist.CtMethod;
import org.apache.ibatis.javassist.Modifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavassistHelp {
	
	private static Logger log = LoggerFactory.getLogger(JavassistHelp.class);
	
	public static ClassPool pool = ClassPool.getDefault();
	
	public static CtClass getCtClass(String classPath) throws Exception {
		return pool.getCtClass(classPath);
	}
	
	public static void addFieldAndAddGetSetMethod(CtClass ctClass,String fieldName) {
		try {
			String getsetName =fieldName.substring(0,1).toUpperCase() +fieldName.substring(1);
			
			CtField newField = new CtField(pool.get("java.lang.String"), fieldName, ctClass);
			newField.setModifiers(Modifier.PRIVATE);
			ctClass.addField(newField);
			
			//为value变量添加set方法
			CtMethod setValue = new CtMethod(CtClass.voidType, "set"+getsetName, new CtClass[]{pool.get("java.lang.String")}, ctClass);
			setValue.setModifiers(Modifier.PUBLIC);
			//设置方法体
			setValue.setBody("this."+fieldName+" = $1;");

			ctClass.addMethod(setValue);

			//为value变量添加get方法
			CtMethod getValue = new CtMethod(pool.get("java.lang.String"), "get"+getsetName, new CtClass[]{}, ctClass);
			getValue.setModifiers(Modifier.PUBLIC);
			//设置方法体
			getValue.setBody("return this."+fieldName+";");
			ctClass.addMethod(getValue);
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
}
